package com.zq.config;


import com.rabbitmq.client.ReturnCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AutoConfig {
    @Autowired
    private CachingConnectionFactory connectionFactory;
    private static final Logger logger= LoggerFactory.getLogger(AutoConfig.class);

//    @Bean(name = "simpleRabbitListenerContainerFactoryAuto")
//    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(ConnectionFactory connectionFactory){
//        SimpleRabbitListenerContainerFactory containerFactory = new SimpleRabbitListenerContainerFactory();
//        containerFactory.setConnectionFactory(connectionFactory);
//        containerFactory.setMessageConverter(new Jackson2JsonMessageConverter());
//        containerFactory.setAcknowledgeMode(AcknowledgeMode.AUTO);
//        return containerFactory;
//
//    }
    //创建队列
    @Bean(name="autoQueue")
    public Queue autoQueue(){
        return new Queue("autoQueue", true);
    }
    //创建交换机
    @Bean("autoEx")
    public DirectExchange directExchange(){
        return new DirectExchange("autoEx", true, false);
    }
    //绑定
    @Bean
    public Binding binding(){
        return BindingBuilder.bind(autoQueue()).to(directExchange()).with("autoQueue");

    }

    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                logger.debug(correlationData+"------------"+b+"------------"+s);
            }
        });
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                logger.error("info send queue error"+s1+"---"+s2);
            }
        });
        return rabbitTemplate;

    }

}
